package com.ruyuan.seckilling.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruyuan.seckilling.activity.constant.ActivityStatusVal;
import com.ruyuan.seckilling.activity.entity.Activity;
import com.ruyuan.seckilling.activity.mapper.ActivityMapper;
import com.ruyuan.seckilling.activity.request.ActivityModifyRequest;
import com.ruyuan.seckilling.activity.request.ActivityQueryPageRequest;
import com.ruyuan.seckilling.activity.service.ActivityService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zhonghuashishan
 */
@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public Activity queryById(Long id) {
        return activityMapper.selectById(id);
    }

    /**
     * 在此时此刻，用户需要看到2种类型的秒杀活动
     * 1. 还未开始的但是已经到了展示时间了，showTime <= now
     * 2. 已经开始了的但是还没结束的，endTime >= now
     */
    @Override
    public List<Activity> queryShowableList() {
        String now = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(new Date());
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("show_time", now);
        queryWrapper.ge("end_time", now);
        queryWrapper.eq("status", ActivityStatusVal.INVENTORY_SYNCED.getCode());
        return activityMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<Activity> queryPage(ActivityQueryPageRequest request) {
        Page<Activity> page = new Page<>(request.getPageNum(), request.getPageSize());
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(request.getActivityName())) {
            queryWrapper.eq("activity_name", request.getActivityName());
        }
        if (StringUtils.isNotBlank(request.getMinStartTime())) {
            queryWrapper.ge("start_time", request.getMinStartTime());
        }
        if (StringUtils.isNotBlank(request.getMaxStartTime())) {
            queryWrapper.le("start_time", request.getMaxStartTime());
        }
        return activityMapper.selectPage(page, queryWrapper);
    }

    /**
     * 1. 距离展示时间还有1小时
     * 2. 状态是已审核的
     */
    @Override
    public List<Activity> queryListForTriggerPageTask() {
        Date showTime = DateUtils.addHours(new Date(), 1);
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("show_time", showTime);
        queryWrapper.eq("status", ActivityStatusVal.AUDIT_PASS.getCode());
        return activityMapper.selectList(queryWrapper);
    }

    /**
     * 1. 状态是PAGE_RENDERING的
     * 2. 更新时间在1min以前的
     */
    @Override
    public List<Activity> queryListForPageFailedCompensationTask() {
        Date updateTime = DateUtils.addMinutes(new Date(), 1);
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("update_time", updateTime);
        queryWrapper.eq("status", ActivityStatusVal.PAGE_RENDERING.getCode());
        return activityMapper.selectList(queryWrapper);
    }

    /**
     * 状态是已渲染好页面的
     */
    @Override
    public List<Activity> queryListForTriggerStockTask() {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", ActivityStatusVal.PAGE_RENDERED.getCode());
        return activityMapper.selectList(queryWrapper);
    }

    /**
     * 状态是库存已同步的
     * 结束时间已经过了1小时的
     */
    @Override
    public List<Activity> queryListForCleanDataTask() {
        Date endTime = DateUtils.addHours(new Date(), -1);
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("end_time", endTime);
        queryWrapper.eq("status", ActivityStatusVal.INVENTORY_SYNCED.getCode());
        return activityMapper.selectList(queryWrapper);
    }

    @Override
    public void save(Activity activity) {
        activity.setCreateTime(new Date());
        activity.setUpdateTime(activity.getCreateTime());
        activityMapper.insert(activity);
    }

    @Override
    public void modify(ActivityModifyRequest request) {
        Activity.ActivityBuilder builder = Activity.builder().id(request.getActivityId());
        if (StringUtils.isNotBlank(request.getActivityName())) {
            builder.activityName(request.getActivityName());
        }
        if (Objects.nonNull(request.getStartTime())) {
            builder.startTime(request.getStartTime());
        }
        if (Objects.nonNull(request.getEndTime())) {
            builder.endTime(request.getEndTime());
        }
        activityMapper.updateById(builder.build());
    }

    @Override
    public boolean updataStatus(Long activityId, Integer oldStatus, Integer newStatus) {
        Activity activity = Activity.builder().status(newStatus).build();
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", activityId);
        if (Objects.nonNull(oldStatus)) {
            queryWrapper.eq("status", oldStatus);
        }
        int affectedRows = activityMapper.update(activity, queryWrapper);
        return affectedRows == 1;
    }

    @Override
    public boolean updataPageReady(Long activityId, boolean pageReady) {
        Activity activity = Activity.builder().id(activityId).pageReady(pageReady).build();
        return activityMapper.updateById(activity) == 1;
    }

    @Override
    public void remove(Long id) {
        activityMapper.deleteById(id);
    }

}
